package com.sun.filesigndemo.common.security.Filter;

import org.springframework.stereotype.Service;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.PrintWriter;

@Service
public class UserAuthFilter extends org.apache.shiro.web.filter.authc.UserFilter {

	@Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws IOException {
		String header = ((HttpServletRequest) request).getHeader("X-Requested-With");
		if(header != null && header.equals("XMLHttpRequest")){
			response.setCharacterEncoding("UTF-8");
			PrintWriter out= null;
				try {
					out = response.getWriter();
					out.print("{\"code\" : 403, \"message\" : \"请先登录\" }");
					out.flush();
				} catch (IOException e) {

				}
				finally {
					if (out != null) {
						out.close();
					}
				}
		} else {
			super.redirectToLogin(request, response);
		}
        return false;
    }
}
